import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Table, Button, Card, Row, Col, message, Modal, Form, Input, InputNumber, Select, Tag, Space, Spin, Progress, Tooltip } from 'antd';
import { ReloadOutlined, DatabaseOutlined, DeleteOutlined, EyeOutlined, ExclamationCircleOutlined, LeftOutlined, RightOutlined, LockOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useSpring, animated } from '@react-spring/web';
import { API_BASE_URL } from '../config';

const { Option } = Select;

// 样例数据样式定义
const sampleDataStyles = `
  .sample-data-container {
    height: 100%;
    background-color: #fff;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .data-table {
    width: 100%;
  }
  
  .table-row-normal-height td {
    padding: 16px 8px;
  }
  
  .table-row-compact-height td {
    padding: 8px;
  }
  
  .compact-table .ant-table-thead > tr > th {
    padding: 8px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-top: 1px solid #e8e8e8;
  }
  
  .table-header-actions {
    padding: 16px;
    display: flex;
    justify-content: flex-end;
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
  }
  
  /* 移动端适配样式 */
  @media (max-width: 576px) {
    .sample-data-container {
      margin: 0;
      border-radius: 0;
    }
    
    .table-header-actions {
      padding: 8px;
      flex-direction: column;
      align-items: flex-start;
    }
    
    .table-header-actions h2 {
      margin-bottom: 8px !important;
    }
    
    .action-buttons {
      width: 100%;
      justify-content: space-between;
    }
    
    .action-buttons button {
      padding: 0 8px;
    }
    
    .compact-table .ant-table-cell {
      padding: 4px !important;
      font-size: 12px !important;
    }
    
    .pagination-container {
      padding: 8px;
    }
    
    .pagination-container > div:first-child {
      font-size: 12px;
    }
  }
`;

const SampleData = () => {
  const [loading, setLoading] = useState(false);
  const [jobList, setJobList] = useState([]);
  const [allJobs, setAllJobs] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [generateModalVisible, setGenerateModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [currentJobId, setCurrentJobId] = useState(null);
  const [currentJob, setCurrentJob] = useState(null);
  const [form] = Form.useForm();
  const [isMobile, setIsMobile] = useState(false);
  const [pollingJobs, setPollingJobs] = useState([]);
  const [confirmJobId, setConfirmJobId] = useState(null);
  const [confirmModalVisible, setConfirmModalVisible] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const inputRef = useRef(null);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [actionType, setActionType] = useState(null);
  const [targetJobId, setTargetJobId] = useState(null);
  const [passwordForm] = Form.useForm();
  const clearDataTimerRef = useRef(null); // 添加定时器引用
  const [loadingJobDetail, setLoadingJobDetail] = useState(false); // 添加任务详情加载状态
  const [jobDetailError, setJobDetailError] = useState(null); // 添加任务详情错误状态
  // 定义常量
  const MAX_RETRIES = 2;
  const RETRY_DELAY = 1500; // 1.5秒后重试
  
  // 动画效果
  const fadeAnimation = useSpring({
    from: { opacity: 0, transform: 'translateY(20px)' },
    to: { opacity: 1, transform: 'translateY(0)' },
    delay: 200,
  });
  
  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 初始加载任务列表
  useEffect(() => {
    fetchJobList();
  }, []);

  // 轮询状态为running的任务
  useEffect(() => {
    const runningJobIds = jobList
      .filter(job => job.status === 'running')
      .map(job => job.job_id);
    
    setPollingJobs(runningJobIds);
  }, [jobList]);

  // 轮询任务状态
  useEffect(() => {
    if (pollingJobs.length === 0) return;
    
    const interval = setInterval(() => {
      pollingJobs.forEach(jobId => {
        fetchJobStatus(jobId);
      });
    }, 3000);
    
    return () => clearInterval(interval);
  }, [pollingJobs]);

  // 更新当前页数据
  useEffect(() => {
    if (allJobs.length > 0) {
      updatePageData(allJobs, currentPage);
    }
  }, [currentPage, pageSize, allJobs]);

  // 获取任务列表
  const fetchJobList = async () => {
    setLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/sample_data/jobs`);
      if (response.data) {
        // 保存所有任务数据
        setAllJobs(response.data);
        
        // 更新分页信息
        setPagination({
          ...pagination,
          total: response.data.length
        });
        
        // 手动实现分页
        updatePageData(response.data, currentPage);
      } else {
        message.error('获取任务列表失败');
      }
    } catch (error) {
      console.error('获取任务列表出错:', error);
      message.error('获取任务列表出错');
    } finally {
      setLoading(false);
    }
  };

  // 手动分页处理
  const updatePageData = (data, page) => {
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const currentPageData = data.slice(startIndex, endIndex);
    setJobList(currentPageData);
  };

  // 处理页码变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  // 处理页码输入
  const handlePageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value)) {
      setCurrentPage(value);
    }
  };

  // 处理页码输入框按键事件
  const handlePageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
        setCurrentPage(value);
      }
    }
  };

  // 前一页
  const goPrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  // 后一页
  const goNextPage = () => {
    if (currentPage < Math.ceil(pagination.total / pageSize)) {
      setCurrentPage(currentPage + 1);
    }
  };

  // 获取任务状态
  const fetchJobStatus = async (jobId) => {
    try {
      const response = await axios.get(`${API_BASE_URL}/api/sample_data/status/${jobId}`);
      if (response.data) {
        // 更新allJobs中的对应任务
        setAllJobs(prevList => {
          const newList = prevList.map(job => 
            job.job_id === jobId ? response.data : job
          );
          
          // 同时更新当前显示的jobList
          updatePageData(newList, currentPage);
          
          return newList;
        });
        
        // 如果是当前查看的任务，也更新它
        if (currentJobId === jobId) {
          setCurrentJob(response.data);
        }
        
        // 如果任务状态不再是running，从轮询列表中移除
        if (response.data.status !== 'running') {
          setPollingJobs(prev => prev.filter(id => id !== jobId));
        }
      }
    } catch (error) {
      console.error(`获取任务状态出错 (${jobId}):`, error);
    }
  };

  // 生成样例数据
  const handleGenerateSampleData = async () => {
    try {
      const values = await form.validateFields();
      setGenerateModalVisible(false);
      
      setLoading(true);
      try {
        const response = await axios.post(`${API_BASE_URL}/api/sample_data/generate`, values);
        if (response.data && response.data.success) {
          message.success(response.data.message);
          fetchJobList();  // 刷新任务列表
        } else {
          message.error('生成样例数据失败');
        }
      } catch (error) {
        console.error('生成样例数据出错:', error);
        message.error('生成样例数据出错');
      } finally {
        setLoading(false);
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 回退样例数据
  const handleRollbackSampleData = async () => {
    if (!confirmJobId) {
      message.error('任务ID不能为空');
      return;
    }
    
    setLoading(true);
    try {
      console.log('发送回退请求，任务ID:', confirmJobId);
      
      // 确保任务ID是字符串类型
      const jobIdString = String(confirmJobId);
      
      const response = await axios.post(`${API_BASE_URL}/api/sample_data/rollback`, {
        job_id: jobIdString
      });
      
      console.log('回退响应:', response);
      
      if (response.data && response.data.success) {
        message.success(response.data.message || '回退样例数据成功');
        fetchJobList();  // 刷新任务列表
        setConfirmModalVisible(false);
      } else {
        message.error(response.data?.message || '回退样例数据失败');
      }
    } catch (error) {
      console.error('回退样例数据出错:', error);
      // 显示更详细的错误信息
      if (error.response) {
        console.error('错误响应数据:', error.response.data);
        // 处理任务ID不存在的情况
        if (error.response.data?.detail && error.response.data.detail.includes('未找到任务ID')) {
          message.error('该任务ID不存在，可能已被删除。请刷新列表后重试。');
          fetchJobList(); // 自动刷新列表
        } else {
          const errorMsg = error.response.data?.detail || 
                          error.response.data?.message || 
                          `请求失败: ${error.response.status}`;
          message.error(errorMsg);
        }
      } else if (error.request) {
        message.error('服务器未响应请求');
      } else {
        message.error(`请求错误: ${error.message}`);
      }
      setConfirmModalVisible(false); // 关闭确认框
    } finally {
      setLoading(false);
    }
  };

  // 使用useCallback和防抖处理，避免频繁调用
  const fetchJobDetail = useCallback(async (jobId, attempt = 0) => {
    let retryCount = 0;
    
    try {
      if (!jobId) return;
      
      setLoadingJobDetail(true);
      setJobDetailError(null); // 清空之前的错误状态
      
      const response = await axios.get(`${API_BASE_URL}/api/sample_data/status/${jobId}`);
      if (response.data) {
        setCurrentJob(response.data);
        if (attempt > 0) {
          message.success('获取任务详情成功');
        }
      } else {
        if (attempt < MAX_RETRIES) {
          message.warning(`获取任务详情失败，将在${RETRY_DELAY/1000}秒后自动重试(${attempt + 1}/${MAX_RETRIES})...`);
          setTimeout(() => fetchJobDetail(jobId, attempt + 1), RETRY_DELAY);
        } else {
          message.error('获取任务详情失败，请稍后再试');
          setJobDetailError('获取任务详情失败，请稍后刷新重试');
        }
      }
    } catch (error) {
      console.error('获取任务详情出错:', error);
      
      // 检查错误类型
      if (error.message === 'Network Error' || 
         (error.response && error.response.status === 500)) {
        
        // 网络错误或服务器错误时自动重试
        if (attempt < MAX_RETRIES) {
          retryCount++;
          const retryMessage = `服务器正在处理，将在${RETRY_DELAY/1000}秒后自动重试(${attempt + 1}/${MAX_RETRIES})...`;
          message.loading({
            content: retryMessage,
            key: 'retryMessage',
            duration: RETRY_DELAY / 1000,
          });
          
          // 设置重试定时器
          setTimeout(() => fetchJobDetail(jobId, attempt + 1), RETRY_DELAY);
        } else {
          message.error({
            content: '获取任务详情失败，服务器可能正在处理其他请求，请稍后再试',
            key: 'retryMessage',
          });
          setJobDetailError('获取任务详情失败，服务器可能正在处理其他请求');
        }
      } else {
        // 其他错误类型
        let errorMessage = '获取任务详情失败';
        if (error.response) {
          errorMessage += `（状态码: ${error.response.status}）`;
          if (error.response.data && error.response.data.message) {
            errorMessage += `: ${error.response.data.message}`;
          }
        } else if (error.request) {
          errorMessage += ': 服务器未响应';
        } else {
          errorMessage += `: ${error.message}`;
        }
        message.error(errorMessage);
        setJobDetailError(errorMessage);
      }
    } finally {
      if (retryCount === 0 || attempt >= MAX_RETRIES) {
        setLoadingJobDetail(false);
      }
    }
  }, []); // 依赖项

  // 查看任务详情 - 防抖处理
  const handleViewJobDetail = (jobId) => {
    if (!jobId) return;
    
    setCurrentJobId(jobId);
    setDetailModalVisible(true);
    setCurrentJob(null); // 清空之前的数据，显示加载状态
    setJobDetailError(null); // 清空之前的错误信息
    
    fetchJobDetail(jobId, 0);
  };

  // 处理口令验证
  const handlePasswordCheck = async () => {
    try {
      const values = await passwordForm.validateFields();
      if (values.password === 'guoxin') {
        // 口令正确，执行对应操作
        setPasswordModalVisible(false);
        passwordForm.resetFields();
        
        if (actionType === 'generate') {
          showGenerateModal();
        } else if (actionType === 'rollback') {
          showConfirmRollback(targetJobId);
        }
      } else {
        // 口令错误，显示错误提示并震动输入框
        passwordForm.setFields([
          {
            name: 'password',
            errors: ['口令错误，请重新输入'],
            value: values.password
          }
        ]);
        
        // 直接在表单上显示错误，同时显示全局消息提示
        message.error({
          content: '口令验证失败，请输入正确的口令',
          style: {
            marginTop: '20vh',
          },
          duration: 3
        });
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };
  
  // 打开生成样例数据模态框前先验证口令
  const verifyBeforeGenerate = () => {
    setActionType('generate');
    setPasswordModalVisible(true);
  };
  
  // 显示生成样例数据模态框
  const showGenerateModal = () => {
    setGenerateModalVisible(true);
  };
  
  // 回退前先验证口令
  const verifyBeforeRollback = (jobId) => {
    setActionType('rollback');
    setTargetJobId(jobId);
    setPasswordModalVisible(true);
  };
  
  // 确认回退
  const showConfirmRollback = (jobId) => {
    // 先刷新列表，确保有最新数据
    fetchJobList().then(() => {
      // 检查任务是否存在
      const jobItem = allJobs.find(j => j.job_id === jobId);
      
      if (!jobItem) {
        message.error('任务ID不存在，请刷新列表后重试');
        return;
      }
      
      // 检查任务状态，如果是running则不允许回退
      if (jobItem.status === 'running') {
        message.warning('正在运行的任务无法回退，请等待任务完成');
        return;
      }
      
      setConfirmJobId(jobId);
      setConfirmModalVisible(true);
    });
  };
  
  // 处理确认回退
  const handleConfirmRollback = () => {
    if (confirmJobId) {
      handleRollbackSampleData();
    }
    // Note: setConfirmModalVisible(false) moved to handleRollbackSampleData on success
  };

  // 刷新任务列表
  const handleRefreshData = () => {
    fetchJobList();
  };

  // 格式化时间
  const formatDateTime = (isoString) => {
    if (!isoString) return '-';
    const date = new Date(isoString);
    return date.toLocaleString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit', 
      minute: '2-digit', 
      second: '2-digit',
      hour12: false
    });
  };

  // 渲染状态标签
  const renderStatusTag = (status) => {
    let color = 'default';
    let text = '未知';
    
    switch(status) {
      case 'running':
        color = 'processing';
        text = '运行中';
        break;
      case 'completed':
        color = 'success';
        text = '已完成';
        break;
      case 'failed':
        color = 'error';
        text = '失败';
        break;
      default:
        break;
    }
    
    return <Tag color={color}>{text}</Tag>;
  };

  // 任务列表列定义
  const columns = [
    {
      title: '任务ID',
      dataIndex: 'job_id',
      key: 'job_id',
      ellipsis: true,
      render: (text) => <Tooltip title={text}>{text.substring(0, 8)}...</Tooltip>
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => renderStatusTag(status),
    },
    {
      title: '进度',
      dataIndex: 'progress',
      key: 'progress',
      render: (progress, record) => (
        <Progress 
          percent={progress} 
          size="small" 
          status={record.status === 'failed' ? 'exception' : undefined} 
          format={(percent) => `${percent.toFixed(0)}%`}
        />
      ),
      responsive: ['md'],
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      key: 'start_time',
      render: (time) => formatDateTime(time),
      responsive: ['lg'],
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      key: 'end_time',
      render: (time) => formatDateTime(time),
      responsive: ['lg'],
    },
    {
      title: '操作',
      key: 'action',
      width: isMobile ? 80 : 120,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="text" 
            icon={<EyeOutlined />} 
            onClick={() => handleViewJobDetail(record.job_id)}
            title="查看详情"
          />
          <Button 
            type="text" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => verifyBeforeRollback(record.job_id)}
            disabled={record.status === 'running'}
            title="回退数据"
          />
        </Space>
      ),
    },
  ];

  // 移动端专用列定义
  const getMobileColumns = () => {
    if (!isMobile) return columns;
    
    return [
      {
        title: '任务',
        key: 'mobile-combined',
        render: (_, record) => (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Tooltip title={record.job_id}>
                <span style={{ fontWeight: 'bold' }}>{record.job_id.substring(0, 8)}...</span>
              </Tooltip>
              {renderStatusTag(record.status)}
            </div>
            <Progress 
              percent={record.progress} 
              size="small" 
              status={record.status === 'failed' ? 'exception' : undefined} 
              format={(percent) => `${percent.toFixed(0)}%`}
            />
            <div style={{ fontSize: '11px', color: '#888' }}>
              {formatDateTime(record.start_time)}
            </div>
          </div>
        )
      },
      columns[5] // 保留操作列
    ];
  };

  // 生成样例数据表单
  const renderGenerateForm = () => (
    <Form form={form} layout="vertical" initialValues={{ count: 1 }}>
      <Form.Item
        name="product_type"
        label={<span style={{ fontSize: isMobile ? '13px' : '14px' }}>产品类型</span>}
        rules={[{ required: true, message: '请选择产品类型' }]}
      >
        <Select 
          placeholder="请选择产品类型" 
          size={isMobile ? 'small' : 'middle'}
        >
          <Option value="cylindrical_cell">圆柱电芯</Option>
          <Option value="prismatic_cell">方形电芯</Option>
          <Option value="pouch_cell">软包电芯</Option>
          <Option value="battery_pack">电池包</Option>
        </Select>
      </Form.Item>
      <Form.Item
        name="sample_type"
        label={<span style={{ fontSize: isMobile ? '13px' : '14px' }}>样例数据类型</span>}
        rules={[{ required: true, message: '请选择样例数据类型' }]}
      >
        <Select 
          placeholder="请选择样例数据类型" 
          size={isMobile ? 'small' : 'middle'}
        >
          <Option value="product_only">仅产品及BOM</Option>
          <Option value="full_sample">完整数据(含工艺模板和路线)</Option>
        </Select>
      </Form.Item>
      <Form.Item
        name="count"
        label={<span style={{ fontSize: isMobile ? '13px' : '14px' }}>生成数量</span>}
        rules={[
          { required: true, message: '请输入生成数量' }
        ]}
      >
        <InputNumber 
          min={1} 
          max={50} 
          placeholder="请输入生成数量(1-50)" 
          style={{ width: '100%' }}
          size={isMobile ? 'small' : 'middle'}
        />
      </Form.Item>
      <Form.Item
        name="description"
        label={<span style={{ fontSize: isMobile ? '13px' : '14px' }}>数据描述</span>}
      >
        <Input.TextArea 
          rows={isMobile ? 3 : 4} 
          placeholder="请输入数据描述(可选)" 
          size={isMobile ? 'small' : 'middle'}
        />
      </Form.Item>
    </Form>
  );

  // 任务详情展示
  const renderJobDetail = () => {
    // 显示加载状态
    if (!currentJob && !jobDetailError) {
      return (
        <div style={{ textAlign: 'center', padding: '30px 0' }}>
          <Spin tip="正在加载任务详情..." />
          <p style={{ marginTop: 15, color: '#999', fontSize: isMobile ? '12px' : '14px' }}>
            首次加载可能需要较长时间，请耐心等待
          </p>
        </div>
      );
    }
    
    // 显示错误信息
    if (jobDetailError) {
      return (
        <div style={{ textAlign: 'center', padding: '30px 0' }}>
          <ExclamationCircleOutlined style={{ fontSize: 40, color: '#ff4d4f', marginBottom: 16 }} />
          <p style={{ color: '#ff4d4f', fontSize: isMobile ? '14px' : '16px', marginBottom: 24 }}>
            {jobDetailError}
          </p>
          <Button 
            type="primary" 
            icon={<ReloadOutlined />} 
            onClick={() => fetchJobDetail(currentJobId, 0)}
          >
            重试
          </Button>
        </div>
      );
    }
    
    // 显示任务详情
    if (currentJob) {
      const styles = {
        jobDetail: {
          padding: isMobile ? '5px' : '10px'
        },
        jobHeader: {
          marginBottom: isMobile ? '10px' : '20px'
        },
        jobStatus: {
          marginTop: '10px'
        },
        jobTime: {
          marginBottom: isMobile ? '10px' : '20px'
        },
        jobCreatedData: {
          marginBottom: isMobile ? '10px' : '20px'
        },
        dataList: {
          maxHeight: isMobile ? '150px' : '200px',
          overflowY: 'auto',
          border: '1px solid #f0f0f0',
          padding: isMobile ? '5px' : '10px',
          marginTop: '10px',
          fontSize: isMobile ? '12px' : 'inherit'
        },
        dataItem: {
          padding: isMobile ? '3px 0' : '5px 0',
          borderBottom: '1px solid #f0f0f0'
        },
        lastDataItem: {
          padding: isMobile ? '3px 0' : '5px 0',
          borderBottom: 'none'
        },
        jobErrors: {
          marginTop: isMobile ? '10px' : '20px',
          color: '#ff4d4f',
          fontSize: isMobile ? '12px' : 'inherit'
        },
        errorItem: {
          marginBottom: isMobile ? '3px' : '5px'
        }
      };
      
      return (
        <div style={styles.jobDetail}>
          <div style={styles.jobHeader}>
            <h3 style={{ fontSize: isMobile ? '14px' : '16px' }}>任务ID: {currentJob.job_id}</h3>
            <div style={styles.jobStatus}>
              {renderStatusTag(currentJob.status)}
              <Progress 
                percent={currentJob.progress} 
                status={currentJob.status === 'failed' ? 'exception' : undefined} 
                size={isMobile ? 'small' : 'default'}
              />
            </div>
          </div>
          
          <div style={styles.jobTime}>
            <p style={{ fontSize: isMobile ? '12px' : 'inherit', margin: isMobile ? '5px 0' : '8px 0' }}>
              <strong>开始时间:</strong> {formatDateTime(currentJob.start_time)}
            </p>
            <p style={{ fontSize: isMobile ? '12px' : 'inherit', margin: isMobile ? '5px 0' : '8px 0' }}>
              <strong>结束时间:</strong> {formatDateTime(currentJob.end_time) || '未结束'}
            </p>
          </div>
          
          {currentJob.details && (
            <div style={styles.jobCreatedData}>
              <h4 style={{ fontSize: isMobile ? '13px' : '14px' }}>已创建数据:</h4>
              {currentJob.details.created_ids && currentJob.details.created_ids.products && (
                <>
                  <p style={{ fontSize: isMobile ? '12px' : 'inherit', margin: isMobile ? '5px 0' : '8px 0' }}>
                    <strong>产品数量:</strong> {currentJob.details.created_ids.products.length}
                  </p>
                  <div style={styles.dataList}>
                    {currentJob.details.created_ids.products.map((product, index) => (
                      <div 
                        key={index} 
                        style={index === currentJob.details.created_ids.products.length - 1 ? styles.lastDataItem : styles.dataItem}
                      >
                        <p style={{ margin: isMobile ? '2px 0' : '5px 0' }}>
                          ID: {product.id}, 名称: {product.name}, 编码: {product.code}
                        </p>
                      </div>
                    ))}
                  </div>
                </>
              )}
              
              {currentJob.details.created_ids && currentJob.details.created_ids.process_routes && (
                <>
                  <p style={{ fontSize: isMobile ? '12px' : 'inherit', margin: isMobile ? '5px 0' : '8px 0' }}>
                    <strong>工艺路线数量:</strong> {currentJob.details.created_ids.process_routes.length}
                  </p>
                  <div style={styles.dataList}>
                    {currentJob.details.created_ids.process_routes.map((route, index) => (
                      <div 
                        key={index} 
                        style={index === currentJob.details.created_ids.process_routes.length - 1 ? styles.lastDataItem : styles.dataItem}
                      >
                        <p style={{ margin: isMobile ? '2px 0' : '5px 0' }}>
                          ID: {route.id}, 名称: {route.name}, 编码: {route.code}
                        </p>
                      </div>
                    ))}
                  </div>
                </>
              )}
            </div>
          )}
          
          {currentJob.details && currentJob.details.errors && currentJob.details.errors.length > 0 && (
            <div style={styles.jobErrors}>
              <h4 style={{ fontSize: isMobile ? '13px' : '14px' }}>错误信息:</h4>
              <ul style={{ paddingLeft: isMobile ? '15px' : '20px' }}>
                {currentJob.details.errors.map((error, index) => (
                  <li key={index} style={styles.errorItem}>{error}</li>
                ))}
              </ul>
            </div>
          )}
        </div>
      );
    }
    
    // 默认返回空内容
    return null;
  };

  // 获取行样式
  const getRowClassName = () => {
    if (jobList.length >= 10 || isMobile) {
      return "table-row-compact-height";
    }
    return "table-row-normal-height";
  };

  // 自定义分页样式
  const customPaginationStyle = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '16px',
    borderTop: '1px solid #e8e8e8',
    background: '#fff'
  };

  // 处理关闭任务详情模态框
  const handleCloseDetailModal = () => {
    try {
      // 先清除之前可能存在的定时器
      if (clearDataTimerRef.current) {
        clearTimeout(clearDataTimerRef.current);
        clearDataTimerRef.current = null;
      }

      // 先隐藏模态框
      setDetailModalVisible(false);
      
      // 设置新的定时器，延迟清空数据
      clearDataTimerRef.current = setTimeout(() => {
        try {
          setCurrentJob(null);
          setCurrentJobId(null);
          setJobDetailError(null);
          setLoadingJobDetail(false);
        } catch (error) {
          console.error('清理数据时出错:', error);
        } finally {
          clearDataTimerRef.current = null; // 清空定时器引用
        }
      }, 300);
    } catch (error) {
      // 确保即使出错也能关闭模态框
      console.error('关闭模态框出错:', error);
      setDetailModalVisible(false);
      setCurrentJob(null);
      setCurrentJobId(null);
      setJobDetailError(null);
      setLoadingJobDetail(false);
    }
  };
  
  // 强制关闭所有模态框（用于紧急情况）
  const forceCloseAllModals = () => {
    try {
      setDetailModalVisible(false);
      setGenerateModalVisible(false);
      setConfirmModalVisible(false);
      setPasswordModalVisible(false);
      
      // 清理状态
      setCurrentJob(null);
      setCurrentJobId(null);
      setJobDetailError(null);
      setLoadingJobDetail(false);
      
      // 清除定时器
      if (clearDataTimerRef.current) {
        clearTimeout(clearDataTimerRef.current);
        clearDataTimerRef.current = null;
      }
      
      message.success('操作已取消');
    } catch (error) {
      console.error('强制关闭模态框出错:', error);
    }
  };

  // 组件卸载时清除定时器
  useEffect(() => {
    return () => {
      if (clearDataTimerRef.current) {
        clearTimeout(clearDataTimerRef.current);
      }
    };
  }, []);

  // 添加键盘事件监听，支持ESC键关闭模态框
  useEffect(() => {
    const handleKeyDown = (event) => {
      // ESC键码为27
      if (event.keyCode === 27) {
        // 根据当前打开的模态框状态决定关闭哪个
        if (detailModalVisible) {
          handleCloseDetailModal();
        } else if (generateModalVisible) {
          setGenerateModalVisible(false);
        } else if (confirmModalVisible) {
          setConfirmModalVisible(false);
        } else if (passwordModalVisible) {
          setPasswordModalVisible(false);
          passwordForm.resetFields();
        }
      }
    };

    // 添加全局键盘事件监听
    window.addEventListener('keydown', handleKeyDown);

    // 组件卸载时移除事件监听
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [detailModalVisible, generateModalVisible, confirmModalVisible, passwordModalVisible]);

  // 组件主体渲染
  return (
    <Spin spinning={loading}>
      <style dangerouslySetInnerHTML={{ __html: sampleDataStyles }} />
      <div className="sample-data-container" style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <div className="table-header-actions" style={{ 
          display: 'flex', 
          justifyContent: isMobile ? 'flex-start' : 'space-between', 
          alignItems: isMobile ? 'flex-start' : 'center', 
          flexDirection: isMobile ? 'column' : 'row',
          borderBottom: '1px solid #e8e8e8' 
        }}>
          <h2 style={{ 
            margin: isMobile ? '0 0 8px 0' : '0 0 0 16px', 
            fontWeight: 'bold', 
            fontSize: isMobile ? '16px' : '18px', 
            color: '#1766a3' 
          }}>样例数据管理</h2>
          <div className="action-buttons" style={{ 
            width: isMobile ? '100%' : 'auto',
            justifyContent: isMobile ? 'space-between' : 'flex-end'
          }}>
            <Button 
              icon={<ReloadOutlined />} 
              onClick={handleRefreshData}
              loading={loading}
              size={isMobile ? 'small' : 'middle'}
            >
              {!isMobile && "刷新"}
            </Button>
            <Button 
              type="primary"
              icon={<DatabaseOutlined />} 
              onClick={verifyBeforeGenerate}
              size={isMobile ? 'small' : 'middle'}
            >
              {isMobile ? "生成" : "生成样例数据"}
            </Button>
          </div>
        </div>
        
        <div style={{ flex: 1, overflow: 'auto' }}>
          <Table
            className={`data-table ${jobList.length >= 10 || isMobile ? 'compact-table' : ''}`}
            columns={isMobile ? getMobileColumns() : columns}
            dataSource={jobList}
            rowKey="job_id"
            pagination={false}
            loading={loading}
            rowClassName={getRowClassName}
            size={isMobile || jobList.length >= 10 ? 'small' : 'middle'}
            bordered={true}
            scroll={{ x: isMobile ? 'max-content' : 'max-content' }}
          />
        </div>
        
        {/* 自定义分页 */}
        <div style={customPaginationStyle} className="pagination-container">
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ fontSize: isMobile ? '12px' : '14px' }}>
              共 {pagination.total} 条{!isMobile && `，${Math.ceil(pagination.total / pageSize)} 页`}
            </span>
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Button 
              icon={<LeftOutlined />}
              onClick={goPrevPage}
              disabled={currentPage === 1}
              style={{ marginRight: isMobile ? '4px' : '8px' }}
              size={isMobile ? 'small' : 'middle'}
            />
            
            <Input
              ref={inputRef}
              style={{ 
                width: isMobile ? '40px' : '50px', 
                textAlign: 'center', 
                margin: isMobile ? '0 4px' : '0 8px',
                fontSize: isMobile ? '12px' : '14px'
              }}
              value={currentPage}
              onChange={handlePageInputChange}
              onKeyPress={handlePageInputKeyPress}
              size={isMobile ? 'small' : 'middle'}
            />
            
            <span style={{ margin: isMobile ? '0 4px' : '0 8px', fontSize: isMobile ? '12px' : '14px' }}>
              / {Math.ceil(pagination.total / pageSize)}
            </span>
            
            <Button 
              icon={<RightOutlined />}
              onClick={goNextPage}
              disabled={currentPage >= Math.ceil(pagination.total / pageSize)}
              style={{ marginLeft: isMobile ? '4px' : '8px', marginRight: isMobile ? '4px' : '8px' }}
              size={isMobile ? 'small' : 'middle'}
            />
            
            {!isMobile && (
              <span style={{ marginLeft: '8px', fontSize: isMobile ? '12px' : '14px' }}>
                {pageSize} / page
              </span>
            )}
          </div>
        </div>
      </div>

      {/* 任务详情模态框 - 优化移动端显示 */}
      <Modal
        title="任务详情"
        open={detailModalVisible}
        onCancel={handleCloseDetailModal}
        footer={[
          <Button key="close" onClick={handleCloseDetailModal}>
            关闭
          </Button>
        ]}
        width={isMobile ? '95%' : 700}
        maskClosable={false}
        destroyOnHidden={true}
      >
        {renderJobDetail()}
      </Modal>
      
      {/* 口令验证模态框 */}
      <Modal
        title="安全验证"
        open={passwordModalVisible}
        onOk={handlePasswordCheck}
        onCancel={() => {
          setPasswordModalVisible(false);
          passwordForm.resetFields();
        }}
        okText="确认"
        cancelText="取消"
        width={isMobile ? '90%' : 400}
      >
        <Form 
          form={passwordForm} 
          layout="vertical"
          onFinish={handlePasswordCheck}
        >
          <Form.Item
            name="password"
            label={<span style={{ fontSize: isMobile ? '13px' : '14px' }}>请输入操作口令</span>}
            rules={[{ required: true, message: '请输入口令' }]}
            help={<span style={{ fontSize: isMobile ? '12px' : '14px' }}>口令输入正确后方可执行操作</span>}
          >
            <Input.Password 
              prefix={<LockOutlined />} 
              placeholder="请输入口令" 
              autoComplete="off"
              autoFocus={true}
              onPressEnter={handlePasswordCheck}
              size={isMobile ? 'small' : 'middle'}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 生成样例数据模态框 */}
      <Modal
        title="生成样例数据"
        open={generateModalVisible}
        onOk={handleGenerateSampleData}
        onCancel={() => setGenerateModalVisible(false)}
        confirmLoading={loading}
        width={isMobile ? '90%' : 520}
      >
        {renderGenerateForm()}
      </Modal>
      
      {/* 确认回退模态框 */}
      <Modal
        title="确认回退样例数据"
        open={confirmModalVisible}
        onOk={handleConfirmRollback}
        onCancel={() => setConfirmModalVisible(false)}
        okText="确认回退"
        cancelText="取消"
        confirmLoading={loading}
        width={isMobile ? '90%' : 400}
      >
        <p style={{ fontSize: isMobile ? '13px' : '14px' }}>回退操作会删除所有生成的数据，且不可恢复，确认继续吗？</p>
        <p style={{ fontSize: isMobile ? '13px' : '14px', wordBreak: 'break-all' }}>任务ID: {confirmJobId}</p>
      </Modal>
    </Spin>
  );
};

export default SampleData; 